import { EXTENSION_PATH, getExtensionConfig, getFrameworkConfig, readJsonFile, writeJsonFile } from './utils';

import fs from 'fs';
import path from 'path';
import { FrameworkConfigurator } from './framework-config';

const econfig = getExtensionConfig();

/**
 * 配置初始化
 */
async function initConfig() {
    // 初始化模块配置
    if (!(await Editor.Profile.getProject(econfig.name, 'modules.__init__'))) {
        //
        let frameworkConfig = new FrameworkConfigurator(getFrameworkConfig());
        frameworkConfig.keepDefaultModules();
        let keepModules = frameworkConfig.collectModules();
        for (let module of keepModules) {
            if (!module.baseModule) {
                await Editor.Profile.setProject(econfig.name, 'modules.' + module.name, true);
            }
        }
        await Editor.Profile.setProject(econfig.name, 'modules.__init__', true);
    }

    // 修改项目 importMap
    let projectFile = path.join(Editor.Project.path, 'settings', 'v2', 'packages', 'project.json');
    let project = readJsonFile(projectFile);
    if (project) {
        let script = project.script;
        if (!script) {
            script = Object.create(null);
            project.script = script;
        }
        let importMap = script.importMap;
        if (!importMap) {
            importMap = 'project://import-map.json';
            script.importMap = importMap;
            writeJsonFile(projectFile, project);
        }
        let importMapFile = importMap.replace('project:/', Editor.Project.path);
        let importMapContent = readJsonFile(importMapFile);
        if (!importMapContent) {
            importMapContent = {};
        }
        let imports = importMapContent.imports;
        if (!imports) {
            imports = Object.create(null);
            importMapContent.imports = imports;
        }
        let relativePath = path
            .relative(path.dirname(importMapFile), `${EXTENSION_PATH}/assets/scripts/`)
            .replace(/\\/g, '/');
        let importsLcc = `./${relativePath}/lcc.ts`;
        if (imports.lcc !== importsLcc) {
            imports.lcc = importsLcc;
            writeJsonFile(importMapFile, importMapContent, 4);
        }
    } else {
        console.error('项目 settings/v2/packages/project.json 未找到');
    }

    // 修改tsconfig.json的paths
    let tsconfigFile = path.join(Editor.Project.path, 'tsconfig.json');
    if (fs.existsSync(tsconfigFile)) {
        let tsconfigContent = fs.readFileSync(tsconfigFile, 'utf-8');
        tsconfigContent = tsconfigContent.replace(/\/\*.*?\*\//g, '');
        tsconfigContent = tsconfigContent.replace(/\/\/.*/g, '');
        let tsconfig = JSON.parse(tsconfigContent);
        if (tsconfig) {
            let compilerOptions = tsconfig.compilerOptions;
            if (!compilerOptions) {
                compilerOptions = Object.create(null);
                tsconfig.compilerOptions = compilerOptions;
            }
            let paths = compilerOptions.paths;
            if (!paths) {
                paths = Object.create(null);
                compilerOptions.paths = paths;
            }
            let relativePath = path
                .relative(path.dirname(tsconfigFile), `${EXTENSION_PATH}/assets/scripts/`)
                .replace(/\\/g, '/');
            let pathsLcc = `./${relativePath}/lcc`;
            if (!paths.lcc || paths.lcc[0] !== pathsLcc) {
                paths.lcc = [pathsLcc];
                writeJsonFile(tsconfigFile, tsconfig, 4);
            }
        }
    } else {
        console.error('项目 tsconfig.json 未找到');
    }

    console.log('LCC配置初始化完成');
}

/**
 * 插件加载回调
 */
export function load() {
    // 当 package 被正确加载的时候执行
    initConfig();
}

/**
 * 插件卸载回调
 */
export function unload() {
    // 当 package 被正确卸载的时候执行
}

/**
 * 插件函数集合
 */
export namespace methods {
    /**
     * 打开设置界面
     */
    export function openFunctions() {
        Editor.Panel.open(`${econfig.name}.functions`);
    }
}
